<template>
  <div>
    <el-button type="primary" @click="handlePrint" :loading="printing">
      <el-icon><Printer /></el-icon>
      打印订单
    </el-button>

    <!-- 打印预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      :title="`${templateType === 'sales' ? '销售' : '采购'}订单打印预览`"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="print-toolbar">
        <el-button-group>
          <el-button @click="handlePrint" type="primary">
            <el-icon><Printer /></el-icon>
            打印
          </el-button>
          <el-button @click="handleExportPDF">
            <el-icon><Download /></el-icon>
            导出PDF
          </el-button>
          <el-button @click="handleCopy">
            <el-icon><CopyDocument /></el-icon>
            复制
          </el-button>
        </el-button-group>

        <el-radio-group v-model="printLayout" size="small">
          <el-radio-button label="portrait">纵向</el-radio-button>
          <el-radio-button label="landscape">横向</el-radio-button>
        </el-radio-group>

        <el-select v-model="printTemplate" placeholder="选择模板" style="width: 150px;" size="small">
          <el-option label="标准模板" value="standard" />
          <el-option label="简洁模板" value="simple" />
          <el-option label="详细模板" value="detailed" />
        </el-select>
      </div>

      <div 
        ref="printContentRef" 
        class="print-content" 
        :class="[printLayout, printTemplate]"
      >
        <!-- 标准模板 -->
        <div v-if="printTemplate === 'standard'" class="print-template standard-template">
          <!-- 页眉 -->
          <div class="print-header">
            <div class="company-info">
              <h1>{{ companyInfo.name }}</h1>
              <p>{{ companyInfo.address }}</p>
              <p>电话：{{ companyInfo.phone }} | 传真：{{ companyInfo.fax }}</p>
            </div>
            <div class="order-title">
              <h2>{{ templateType === 'sales' ? '销售订单' : '采购订单' }}</h2>
              <div class="barcode">
                <svg ref="barcodeRef"></svg>
              </div>
            </div>
          </div>

          <!-- 订单基本信息 -->
          <div class="order-info-section">
            <table class="info-table">
              <tr>
                <td class="label">订单号：</td>
                <td class="value">{{ orderData.orderNo }}</td>
                <td class="label">日期：</td>
                <td class="value">{{ orderData.createTime }}</td>
              </tr>
              <tr>
                <td class="label">{{ templateType === 'sales' ? '客户' : '供应商' }}：</td>
                <td class="value">{{ templateType === 'sales' ? orderData.customerName : orderData.supplierName }}</td>
                <td class="label">{{ templateType === 'sales' ? '销售员' : '采购员' }}：</td>
                <td class="value">{{ templateType === 'sales' ? orderData.salesman : orderData.buyer }}</td>
              </tr>
              <tr v-if="templateType === 'sales'">
                <td class="label">联系电话：</td>
                <td class="value">{{ orderData.contactPhone || '-' }}</td>
                <td class="label">收货地址：</td>
                <td class="value">{{ orderData.deliveryAddress || '-' }}</td>
              </tr>
              <tr>
                <td class="label">预计{{ templateType === 'sales' ? '发货' : '到货' }}：</td>
                <td class="value">{{ orderData.expectedDate }}</td>
                <td class="label">备注：</td>
                <td class="value">{{ orderData.remark || '-' }}</td>
              </tr>
            </table>
          </div>

          <!-- 商品明细 -->
          <div class="products-section">
            <table class="products-table">
              <thead>
                <tr>
                  <th width="60">序号</th>
                  <th width="120">商品编码</th>
                  <th>商品名称</th>
                  <th width="150">规格</th>
                  <th width="80">单位</th>
                  <th width="100">数量</th>
                  <th width="100">单价</th>
                  <th width="120">金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(product, index) in orderData.products" :key="index">
                  <td class="center">{{ index + 1 }}</td>
                  <td>{{ product.productCode }}</td>
                  <td>{{ product.productName }}</td>
                  <td>{{ product.specification }}</td>
                  <td class="center">{{ product.unit }}</td>
                  <td class="right">{{ product.quantity }}</td>
                  <td class="right">¥{{ product.unitPrice.toFixed(2) }}</td>
                  <td class="right">¥{{ (product.quantity * product.unitPrice).toFixed(2) }}</td>
                </tr>
                <!-- 填充空行 -->
                <tr v-for="i in Math.max(0, 10 - orderData.products.length)" :key="'empty-' + i" class="empty-row">
                  <td class="center">{{ orderData.products.length + i }}</td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>
              </tbody>
              <tfoot>
                <tr class="total-row">
                  <td colspan="5" class="right">合计</td>
                  <td class="right">{{ getTotalQuantity() }}</td>
                  <td></td>
                  <td class="right">¥{{ orderData.totalAmount.toFixed(2) }}</td>
                </tr>
                <tr class="amount-words-row">
                  <td colspan="8">
                    金额大写：<span class="amount-words">{{ convertAmountToWords(orderData.totalAmount) }}</span>
                  </td>
                </tr>
              </tfoot>
            </table>
          </div>

          <!-- 页脚签名 -->
          <div class="print-footer">
            <div class="signature-section">
              <div class="signature-item">
                <span class="signature-label">制单人：</span>
                <span class="signature-line">______________</span>
              </div>
              <div class="signature-item">
                <span class="signature-label">审核人：</span>
                <span class="signature-line">______________</span>
              </div>
              <div class="signature-item">
                <span class="signature-label">{{ templateType === 'sales' ? '客户签收' : '供应商确认' }}：</span>
                <span class="signature-line">______________</span>
              </div>
              <div class="signature-item">
                <span class="signature-label">日期：</span>
                <span class="signature-line">______________</span>
              </div>
            </div>
            <div class="print-date">打印时间：{{ new Date().toLocaleString() }}</div>
          </div>
        </div>

        <!-- 简洁模板 -->
        <div v-if="printTemplate === 'simple'" class="print-template simple-template">
          <div class="simple-header">
            <h2>{{ companyInfo.name }}</h2>
            <h3>{{ templateType === 'sales' ? '销售订单' : '采购订单' }}</h3>
          </div>

          <div class="simple-info">
            <div class="info-row">
              <span>订单号：{{ orderData.orderNo }}</span>
              <span>日期：{{ orderData.createTime }}</span>
            </div>
            <div class="info-row">
              <span>{{ templateType === 'sales' ? '客户' : '供应商' }}：{{ templateType === 'sales' ? orderData.customerName : orderData.supplierName }}</span>
            </div>
          </div>

          <table class="simple-products-table">
            <thead>
              <tr>
                <th width="60">序号</th>
                <th>商品</th>
                <th width="100">数量</th>
                <th width="100">单价</th>
                <th width="120">金额</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(product, index) in orderData.products" :key="index">
                <td class="center">{{ index + 1 }}</td>
                <td>
                  {{ product.productName }}
                  <span class="spec">{{ product.specification }}</span>
                </td>
                <td class="right">{{ product.quantity }} {{ product.unit }}</td>
                <td class="right">¥{{ product.unitPrice.toFixed(2) }}</td>
                <td class="right">¥{{ (product.quantity * product.unitPrice).toFixed(2) }}</td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="4" class="right">总计：</td>
                <td class="right"><strong>¥{{ orderData.totalAmount.toFixed(2) }}</strong></td>
              </tr>
            </tfoot>
          </table>
        </div>

        <!-- 详细模板 -->
        <div v-if="printTemplate === 'detailed'" class="print-template detailed-template">
          <div class="detailed-header">
            <div class="logo-section">
              <div class="company-logo">LOGO</div>
              <div class="company-details">
                <h1>{{ companyInfo.name }}</h1>
                <p>{{ companyInfo.address }}</p>
                <p>电话：{{ companyInfo.phone }}</p>
                <p>邮箱：{{ companyInfo.email }}</p>
              </div>
            </div>
            <div class="order-details">
              <h2>{{ templateType === 'sales' ? '销售订单' : '采购订单' }}</h2>
              <table class="detail-info-table">
                <tr>
                  <td>订单号：</td>
                  <td>{{ orderData.orderNo }}</td>
                </tr>
                <tr>
                  <td>日期：</td>
                  <td>{{ orderData.createTime }}</td>
                </tr>
                <tr>
                  <td>状态：</td>
                  <td>{{ orderData.status }}</td>
                </tr>
              </table>
            </div>
          </div>

          <div class="detailed-parties">
            <div class="party-info">
              <h4>{{ templateType === 'sales' ? '客户信息' : '供应商信息' }}</h4>
              <p>名称：{{ templateType === 'sales' ? orderData.customerName : orderData.supplierName }}</p>
              <p v-if="templateType === 'sales'">电话：{{ orderData.contactPhone || '-' }}</p>
              <p v-if="templateType === 'sales'">地址：{{ orderData.deliveryAddress || '-' }}</p>
            </div>
            <div class="party-info">
              <h4>{{ templateType === 'sales' ? '销售信息' : '采购信息' }}</h4>
              <p>{{ templateType === 'sales' ? '销售员' : '采购员' }}：{{ templateType === 'sales' ? orderData.salesman : orderData.buyer }}</p>
              <p>预计{{ templateType === 'sales' ? '发货' : '到货' }}：{{ orderData.expectedDate }}</p>
              <p>备注：{{ orderData.remark || '-' }}</p>
            </div>
          </div>

          <table class="detailed-products-table">
            <thead>
              <tr>
                <th width="50">序号</th>
                <th width="100">编码</th>
                <th>商品名称</th>
                <th width="120">规格</th>
                <th width="60">单位</th>
                <th width="80">数量</th>
                <th width="100">单价</th>
                <th width="100">折扣</th>
                <th width="120">金额</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(product, index) in orderData.products" :key="index">
                <td class="center">{{ index + 1 }}</td>
                <td>{{ product.productCode }}</td>
                <td>{{ product.productName }}</td>
                <td>{{ product.specification }}</td>
                <td class="center">{{ product.unit }}</td>
                <td class="right">{{ product.quantity }}</td>
                <td class="right">¥{{ product.unitPrice.toFixed(2) }}</td>
                <td class="center">{{ product.discount || '无' }}</td>
                <td class="right">¥{{ (product.quantity * product.unitPrice).toFixed(2) }}</td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="5" class="right">小计：</td>
                <td class="right">{{ getTotalQuantity() }}</td>
                <td colspan="2"></td>
                <td class="right">¥{{ orderData.totalAmount.toFixed(2) }}</td>
              </tr>
              <tr>
                <td colspan="8" class="right">税额：</td>
                <td class="right">¥{{ (orderData.totalAmount * 0.13).toFixed(2) }}</td>
              </tr>
              <tr>
                <td colspan="8" class="right"><strong>总计：</strong></td>
                <td class="right"><strong>¥{{ (orderData.totalAmount * 1.13).toFixed(2) }}</strong></td>
              </tr>
            </tfoot>
          </table>

          <div class="detailed-footer">
            <div class="terms">
              <h4>条款说明：</h4>
              <ol>
                <li>本订单一式两份，双方各执一份。</li>
                <li>货物送达后请仔细验收，如有问题请在24小时内提出。</li>
                <li>付款方式：{{ orderData.paymentMethod || '按合同约定' }}</li>
              </ol>
            </div>
            <div class="signatures">
              <div class="signature-block">
                <p>{{ companyInfo.name }}</p>
                <p>签字：_____________</p>
                <p>日期：_____________</p>
              </div>
              <div class="signature-block">
                <p>{{ templateType === 'sales' ? orderData.customerName : orderData.supplierName }}</p>
                <p>签字：_____________</p>
                <p>日期：_____________</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineProps, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Printer, Download, CopyDocument } from '@element-plus/icons-vue'
import JsBarcode from 'jsbarcode'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

// Props
const props = defineProps({
  orderData: {
    type: Object,
    required: true
  },
  templateType: {
    type: String,
    default: 'sales' // sales or purchase
  },
  visible: {
    type: Boolean,
    default: false
  }
})

// 响应式数据
const previewVisible = ref(props.visible)
const printing = ref(false)
const printLayout = ref('portrait')
const printTemplate = ref('standard')
const printContentRef = ref(null)
const barcodeRef = ref(null)

// 公司信息
const companyInfo = {
  name: 'Big-ERP 企业管理系统',
  address: '北京市朝阳区XX街道XX号',
  phone: '010-88888888',
  fax: '010-88888889',
  email: 'info@bigerp.com'
}

// 监听 visible 变化
watch(() => props.visible, (newVal) => {
  previewVisible.value = newVal
  if (newVal) {
    setTimeout(() => {
      generateBarcode()
    }, 100)
  }
})

// 生成条形码
const generateBarcode = () => {
  if (barcodeRef.value && props.orderData.orderNo) {
    try {
      JsBarcode(barcodeRef.value, props.orderData.orderNo, {
        format: 'CODE128',
        width: 2,
        height: 50,
        displayValue: true,
        fontSize: 14
      })
    } catch (error) {
      console.error('生成条形码失败:', error)
    }
  }
}

// 计算总数量
const getTotalQuantity = () => {
  return props.orderData.products?.reduce((total, product) => {
    return total + (product.quantity || 0)
  }, 0) || 0
}

// 金额转大写
const convertAmountToWords = (amount) => {
  const fraction = ['角', '分']
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  
  let num = Math.abs(amount)
  let s = ''
  
  for (let i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(num * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
  }
  s = s || '整'
  num = Math.floor(num)
  
  for (let i = 0; i < unit[0].length && num > 0; i++) {
    let p = ''
    for (let j = 0; j < unit[1].length && num > 0; j++) {
      p = digit[num % 10] + unit[1][j] + p
      num = Math.floor(num / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  
  return s.replace(/(零.)*零元/, '元')
    .replace(/(零.)+/g, '零')
    .replace(/^整$/, '零元整')
}

// 打印
const handlePrint = () => {
  printing.value = true
  
  setTimeout(() => {
    const printWindow = window.open('', '_blank')
    const styles = `
      <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Microsoft YaHei', Arial, sans-serif; }
        @media print {
          @page { 
            size: ${printLayout.value === 'landscape' ? 'A4 landscape' : 'A4 portrait'};
            margin: 10mm;
          }
          body { print-color-adjust: exact; -webkit-print-color-adjust: exact; }
        }
      </style>
    `
    
    printWindow.document.write('<html><head><title>打印订单</title>')
    printWindow.document.write(styles)
    printWindow.document.write('</head><body>')
    printWindow.document.write(printContentRef.value.innerHTML)
    printWindow.document.write('</body></html>')
    printWindow.document.close()
    
    setTimeout(() => {
      printWindow.print()
      printWindow.close()
      printing.value = false
    }, 500)
  }, 100)
}

// 导出PDF
const handleExportPDF = async () => {
  try {
    ElMessage.info('正在生成PDF...')
    
    const canvas = await html2canvas(printContentRef.value, {
      scale: 2,
      useCORS: true,
      logging: false
    })
    
    const imgData = canvas.toDataURL('image/png')
    const pdf = new jsPDF({
      orientation: printLayout.value === 'landscape' ? 'l' : 'p',
      unit: 'mm',
      format: 'a4'
    })
    
    const imgWidth = printLayout.value === 'landscape' ? 277 : 190
    const imgHeight = (canvas.height * imgWidth) / canvas.width
    
    pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight)
    pdf.save(`${props.orderData.orderNo}.pdf`)
    
    ElMessage.success('PDF导出成功')
  } catch (error) {
    console.error('导出PDF失败:', error)
    ElMessage.error('PDF导出失败')
  }
}

// 复制
const handleCopy = () => {
  const text = printContentRef.value.innerText
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('内容已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}
</script>

<style scoped>
.print-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.print-content {
  background: white;
  padding: 20mm;
  min-height: 297mm;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.print-content.landscape {
  min-height: 210mm;
}

/* 标准模板样式 */
.standard-template {
  font-size: 12px;
  color: #333;
}

.print-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #409EFF;
}

.company-info h1 {
  font-size: 24px;
  color: #409EFF;
  margin-bottom: 8px;
}

.company-info p {
  font-size: 12px;
  color: #666;
  line-height: 1.6;
}

.order-title {
  text-align: right;
}

.order-title h2 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.barcode {
  margin-top: 10px;
}

.order-info-section {
  margin-bottom: 20px;
}

.info-table {
  width: 100%;
  border-collapse: collapse;
}

.info-table td {
  padding: 8px;
  border: 1px solid #e4e7ed;
}

.info-table .label {
  width: 15%;
  background: #f5f7fa;
  font-weight: bold;
  color: #606266;
}

.info-table .value {
  width: 35%;
  color: #303133;
}

.products-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.products-table th,
.products-table td {
  padding: 10px;
  border: 1px solid #e4e7ed;
  font-size: 12px;
}

.products-table th {
  background: #f5f7fa;
  color: #606266;
  font-weight: bold;
  text-align: center;
}

.products-table .center {
  text-align: center;
}

.products-table .right {
  text-align: right;
}

.products-table .empty-row {
  height: 35px;
}

.products-table tfoot {
  background: #f9fafc;
  font-weight: bold;
}

.total-row td {
  font-size: 14px;
  color: #303133;
}

.amount-words-row {
  background: #fff !important;
}

.amount-words {
  color: #e6a23c;
  font-weight: bold;
  margin-left: 10px;
}

.print-footer {
  margin-top: 40px;
}

.signature-section {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.signature-item {
  text-align: center;
}

.signature-label {
  font-weight: bold;
  color: #606266;
}

.signature-line {
  display: inline-block;
  border-bottom: 1px solid #303133;
  min-width: 120px;
  margin-left: 10px;
}

.print-date {
  text-align: right;
  color: #909399;
  font-size: 11px;
}

/* 简洁模板样式 */
.simple-template {
  font-size: 13px;
}

.simple-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 3px double #409EFF;
}

.simple-header h2 {
  font-size: 26px;
  color: #303133;
  margin-bottom: 10px;
}

.simple-header h3 {
  font-size: 20px;
  color: #606266;
}

.simple-info {
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px dashed #e4e7ed;
}

.simple-products-table {
  width: 100%;
  border-collapse: collapse;
}

.simple-products-table th,
.simple-products-table td {
  padding: 12px;
  border: 1px solid #e4e7ed;
}

.simple-products-table th {
  background: #f5f7fa;
  font-weight: bold;
  text-align: center;
}

.simple-products-table .spec {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}

/* 详细模板样式 */
.detailed-template {
  font-size: 12px;
}

.detailed-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 3px solid #409EFF;
}

.logo-section {
  display: flex;
  gap: 15px;
}

.company-logo {
  width: 80px;
  height: 80px;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  border-radius: 8px;
}

.company-details h1 {
  font-size: 20px;
  color: #303133;
  margin-bottom: 8px;
}

.company-details p {
  font-size: 11px;
  color: #606266;
  line-height: 1.6;
}

.order-details h2 {
  font-size: 24px;
  color: #409EFF;
  margin-bottom: 10px;
}

.detail-info-table {
  border-collapse: collapse;
}

.detail-info-table td {
  padding: 4px 8px;
  font-size: 12px;
}

.detail-info-table td:first-child {
  color: #909399;
  font-weight: bold;
}

.detailed-parties {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.party-info {
  padding: 15px;
  background: #f9fafc;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
}

.party-info h4 {
  font-size: 14px;
  color: #303133;
  margin-bottom: 10px;
}

.party-info p {
  font-size: 12px;
  color: #606266;
  line-height: 1.8;
}

.detailed-products-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.detailed-products-table th,
.detailed-products-table td {
  padding: 10px;
  border: 1px solid #e4e7ed;
  font-size: 12px;
}

.detailed-products-table th {
  background: #ecf5ff;
  color: #409EFF;
  font-weight: bold;
  text-align: center;
}

.detailed-footer {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  margin-top: 30px;
}

.terms h4 {
  font-size: 14px;
  color: #303133;
  margin-bottom: 10px;
}

.terms ol {
  padding-left: 20px;
}

.terms li {
  font-size: 12px;
  color: #606266;
  line-height: 1.8;
  margin-bottom: 5px;
}

.signatures {
  display: flex;
  gap: 20px;
}

.signature-block {
  flex: 1;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.signature-block p {
  font-size: 12px;
  color: #606266;
  line-height: 2;
}
</style>

